import {childProcess, fileSys, operationSystem, path} from "./NodeEnhance";

const projectName = process.argv[2];
if (!projectName) {
    console.error("project name is empty");
    process.exit(100);
}
const projectRepository = path.join(operationSystem.homedir(), "project-code");
const projectDir = projectRepository + "/" + projectName;

const webpackModuleList = [
    "webpack",
    "webpack-cli",
    "webpack-dev-server",
];

const webpackPlugin = [
    "terser-webpack-plugin",
    "mini-css-extract-plugin",
    "css-minimizer-webpack-plugin",
    "copy-webpack-plugin",
];

const cssLoader = [
    "css-loader",
    "style-loader",
    "postcss",
    "postcss-loader",
    "autoprefixer",
];

const scssLoader = [
    "node-sass",
    "sass-loader",
];

const tsLoader = [
    "typescript",
    "ts-loader",
];

function copyConfigFile() {
    const configFileList = [
        ".browserslistrc",
        ".gitignore",
        "babel.config.json",
        "base.webpack.config.js",
        "postcss.config.js"
    ];
    return Promise.all(configFileList.map((configFile) => {
        return fileSys.promises.copyFile(path.toPosix(path.join(__dirname, "../static/config", configFile)), path.join(projectDir, configFile));
    }));
}

async function startBuild() {
    await fileSys.mkdirPromise(projectDir);
    if (fileSys.existsSync(projectDir)) {
        await childProcess.execPromise("npm init -y", {
            cwd: projectDir,
        });
        const installCmdStr = `npm install --save-dev ${webpackModuleList.concat(webpackPlugin).concat(cssLoader).concat(scssLoader).concat(tsLoader).join(" ")}`;
        console.log(`cmd exec:[${installCmdStr}]`);
        const installCmd = childProcess.exec(installCmdStr, {
            cwd: projectDir,
        });
        if (installCmd.stdout) {
            installCmd.stdout.on("data", (chunk) => {
                console.log("---data---");
                console.log(chunk);
            });
        }
        fileSys.mkdirPromise(projectDir + "/src").catch((err) => {
            console.error(err);
        });
        return copyConfigFile();
    }
}

startBuild().catch((err) => {
    console.error(err);
});
